package com.zelin.gulimall.product.exception;

import com.zelin.common.exception.BizCodeEnum;
import com.zelin.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2020/12/27 20:15
 */
// @ControllerAdvice(basePackages = "com.zelin.gulimall.product.controller")
// @ResponseBody
//上面两名相当于
@RestControllerAdvice(basePackages = "com.zelin.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {

    //1.校验参数格式
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        //1.根据异常得到绑定的结果集
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            errorMap.put(field,defaultMessage);
        });

        log.error("异常原因：{},异常类型：{}",e.getMessage(),e.getClass());
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",errorMap);
    }

    //2.通用错误校验
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        throwable.printStackTrace();
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
